package mta.command.patch;

import mta.command.CommandIF;
import mta.io.LocalizationPackageWriter;
import mta.io.csv.reader.CsvTranslationReader;
import mta.io.csv.writer.CsvTranslationWriterFactory;
import mta.io.csv.writer.CsvTranslationsWriter;
import mta.localization.LocalizationPackage;
import mta.localization.LocalizationPackageFactory;
import mta.patch.ModulePhrasePatchIF;
import mta.patch.PatchAll;
import mta.patch.PatchUntranslated;
import org.apache.commons.cli.ParseException;

/**
 * Magento Translation Assistant
 * Copyright (c) 2009 Dmitry Nikolaev
 * Contact author: blackliteon@gmail.com
 */
public class PatchBuilder {

    private String[] args;

    public PatchBuilder(String[] args) {
        this.args = args;
    }

    public CommandIF build() {
        PatchBuilderOptions builderOptions = new PatchBuilderOptions(args);
        try {
            builderOptions.parse();
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }

        String localizationPath = builderOptions.getLocalizationPath();
        String filePath = builderOptions.getFilePath();

        LocalizationPackage loc = new LocalizationPackageFactory().build(localizationPath);
        CsvTranslationWriterFactory writerFactory = new CsvTranslationWriterFactory();
        CsvTranslationsWriter writer = new CsvTranslationsWriter(localizationPath, writerFactory);
        LocalizationPackageWriter lWriter = new LocalizationPackageWriter(writer, true);

        ModulePhrasePatchIF patch = null;

        switch (builderOptions.getTypeOfAffectedPhrases()) {

            case All:
                patch = new PatchAll(new CsvTranslationReader(filePath).getPhrases());
                break;
            case Untranslated:
                patch = new PatchUntranslated(loc, new CsvTranslationReader(filePath).getPhrases());
                break;
        }

        return new Patch(loc, patch, lWriter);
    }
}